<template>
  <div class="school-management">
    <!-- 演示模式提示 -->
    <el-alert
      v-if="isDemoMode"
      title="演示模式"
      type="info"
      :closable="false"
      show-icon
      style="margin-bottom: 20px;"
    >
      <template slot="default">
        当前为演示模式，所有操作仅在本地生效，页面刷新后数据将重置。如需持久化数据，请确保后端API已正确配置。
      </template>
    </el-alert>

    <el-card>
      <div slot="header">
        <span>学校管理</span>
        <div style="float: right;">
          <el-button style="padding: 3px 0; margin-right: 10px;" type="text" @click="forceRefresh">
            <i class="el-icon-refresh"></i> 强制刷新
          </el-button>
          <el-button style="padding: 3px 0" type="text" @click="handleAdd">添加学校</el-button>
        </div>
      </div>
      
      <!-- 搜索和筛选区域 -->
      <div class="search-area">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input
              v-model="searchForm.keyword"
              placeholder="搜索学校名称或地址"
              prefix-icon="el-icon-search"
              @keyup.enter.native="handleSearch"
              clearable
            />
          </el-col>
          <el-col :span="4">
            <el-select v-model="searchForm.status" placeholder="选择状态" clearable>
              <el-option label="正常" value="active" />
              <el-option label="禁用" value="disabled" />
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 学校列表 -->
      <el-table
        :data="schoolList"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="学校名称" width="200" />
        <el-table-column prop="address" label="地址" width="250" show-overflow-tooltip />
        <el-table-column prop="contactPhone" label="联系电话" width="150" />
        <el-table-column prop="contactPerson" label="联系人" width="120" />
        <el-table-column prop="studentCount" label="学生数量" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)" size="small">
              {{ getStatusName(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="160">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="400" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleView(scope.row)">查看</el-button>
            <el-button size="mini" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button 
              size="mini" 
              :type="scope.row.status === 'active' ? 'warning' : 'success'"
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.status === 'active' ? '禁用' : '启用' }}
            </el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-area">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
        />
      </div>
    </el-card>

    <!-- 查看学校详情对话框 -->
    <el-dialog :visible.sync="viewDialogVisible" title="学校详情" width="600px">
      <div v-if="currentSchool" class="school-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="学校ID">{{ currentSchool.id }}</el-descriptions-item>
          <el-descriptions-item label="学校名称">{{ currentSchool.name }}</el-descriptions-item>
          <el-descriptions-item label="联系人">{{ currentSchool.contactPerson }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ currentSchool.contactPhone }}</el-descriptions-item>
          <el-descriptions-item label="学生数量">{{ currentSchool.studentCount }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentSchool.status)" size="small">
              {{ getStatusName(currentSchool.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="地址" :span="2">{{ currentSchool.address }}</el-descriptions-item>
          <el-descriptions-item label="创建时间" :span="2">{{ formatDate(currentSchool.createdAt) }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 编辑/添加学校对话框 -->
    <el-dialog 
      :visible.sync="editDialogVisible" 
      :title="isEditing ? '编辑学校' : '添加学校'" 
      width="600px"
      @close="resetForm"
    >
      <el-form 
        :model="schoolForm" 
        :rules="schoolRules" 
        ref="schoolForm" 
        label-width="100px"
      >
        <el-form-item label="学校名称" prop="name">
          <el-input v-model="schoolForm.name" placeholder="请输入学校名称" />
        </el-form-item>
        <el-form-item label="学校地址" prop="address">
          <el-input 
            v-model="schoolForm.address" 
            type="textarea" 
            :rows="3"
            placeholder="请输入学校地址" 
          />
        </el-form-item>
        <el-form-item label="联系人" prop="contactPerson">
          <el-input v-model="schoolForm.contactPerson" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contactPhone">
          <el-input v-model="schoolForm.contactPhone" placeholder="请输入联系电话" />
        </el-form-item>
        <el-form-item label="学生数量" prop="studentCount">
          <el-input-number 
            v-model="schoolForm.studentCount" 
            :min="0" 
            :max="100000"
            controls-position="right"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="schoolForm.status">
            <el-radio label="active">正常</el-radio>
            <el-radio label="disabled">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">
          {{ isEditing ? '保存' : '添加' }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "SchoolManagement",
  data() {
    return {
      loading: false,
      saving: false,
      isDemoMode: false, // 演示模式标记
      schoolList: [],
      searchForm: {
        keyword: "",
        status: ""
      },
      pagination: {
        currentPage: 1,
        pageSize: 20,
        total: 0
      },
      // 对话框控制
      viewDialogVisible: false,
      editDialogVisible: false,
      isEditing: false,
      currentSchool: null,
      // 表单数据
      schoolForm: {
        id: null,
        name: '',
        address: '',
        contactPerson: '',
        contactPhone: '',
        studentCount: 0,
        status: 'active'
      },
      // 表单验证规则
      schoolRules: {
        name: [
          { required: true, message: '请输入学校名称', trigger: 'blur' },
          { min: 2, max: 50, message: '学校名称长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请输入学校地址', trigger: 'blur' },
          { min: 5, max: 200, message: '学校地址长度在 5 到 200 个字符', trigger: 'blur' }
        ],
        contactPerson: [
          { required: true, message: '请输入联系人姓名', trigger: 'blur' },
          { min: 2, max: 20, message: '联系人姓名长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        contactPhone: [
          { required: true, message: '请输入联系电话', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$|^0\d{2,3}-?\d{7,8}$/, message: '请输入正确的电话号码', trigger: 'blur' }
        ],
        studentCount: [
          { required: true, message: '请输入学生数量', trigger: 'blur' },
          { type: 'number', min: 0, max: 100000, message: '学生数量应在 0 到 100000 之间', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      }
    }
  },
  async created() {
    await this.loadSchoolList()
  },
  methods: {
    async loadSchoolList() {
      this.loading = true
      try {
        const params = {
          page: this.pagination.currentPage,
          size: this.pagination.pageSize,
          ...this.searchForm
        }
        const response = await this.$http.get("/admin/schools", { params })
        console.log("学校列表接口响应:", response.data)
        
        if (response.data.code === 200) {
          const data = response.data.data
          console.log("接口返回的数据结构:", data)
          
          // 兼容不同的数据结构
          let schoolList = []
          let total = 0
          
          if (Array.isArray(data)) {
            // 如果data直接是数组
            schoolList = data
            total = data.length
          } else if (data && Array.isArray(data.list)) {
            // 如果data是对象，包含list数组
            schoolList = data.list
            total = data.total || data.list.length
          } else if (data && Array.isArray(data.records)) {
            // 如果使用records字段（PageResult结构）
            schoolList = data.records
            total = data.total || data.records.length
          } else {
            console.warn("未知的数据结构:", data)
            schoolList = []
            total = 0
          }
          
          // 验证数据
          if (this.validateSchoolData(schoolList)) {
            this.schoolList = schoolList
            this.pagination.total = total
          } else {
            console.error("学校数据验证失败，使用模拟数据")
            this.loadMockData()
            return
          }
          
          console.log("解析后的学校列表:", this.schoolList)
          console.log("总数:", this.pagination.total)
        } else {
          console.error("接口返回错误:", response.data.message)
          this.$message.error(response.data.message || "获取学校列表失败")
          this.loadMockData()
        }
      } catch (error) {
        console.error("加载学校列表失败:", error)
        this.$message.error("网络请求失败，使用模拟数据")
        // 使用模拟数据
        this.loadMockData()
      } finally {
        this.loading = false
      }
    },

    loadMockData() {
      console.log("使用模拟数据")
      this.isDemoMode = true // 启用演示模式提示
      this.schoolList = [
        {
          id: 1,
          name: "北京大学",
          address: "北京市海淀区颐和园路5号",
          contactPhone: "010-62751201",
          contactPerson: "张老师",
          studentCount: 30000,
          status: "active",
          createdAt: "2025-09-01T00:00:00"
        },
        {
          id: 2,
          name: "清华大学",
          address: "北京市海淀区清华园1号",
          contactPhone: "010-62782051",
          contactPerson: "李老师",
          studentCount: 25000,
          status: "active",
          createdAt: "2025-09-02T00:00:00"
        },
        {
          id: 3,
          name: "复旦大学",
          address: "上海市杨浦区邯郸路220号",
          contactPhone: "021-65642222",
          contactPerson: "王老师",
          studentCount: 28000,
          status: "active",
          createdAt: "2025-09-03T00:00:00"
        },
        {
          id: 4,
          name: "上海交通大学",
          address: "上海市闵行区东川路800号",
          contactPhone: "021-34200000",
          contactPerson: "刘老师",
          studentCount: 32000,
          status: "active",
          createdAt: "2025-09-04T00:00:00"
        },
        {
          id: 5,
          name: "中山大学",
          address: "广州市海珠区新港西路135号",
          contactPhone: "020-84110000",
          contactPerson: "陈老师",
          studentCount: 27000,
          status: "active",
          createdAt: "2025-09-05T00:00:00"
        }
      ]
      this.pagination.total = this.schoolList.length
      console.log("模拟数据加载完成:", this.schoolList.length + "条记录")
    },

    handleSearch() {
      this.pagination.currentPage = 1
      this.loadSchoolList()
    },

    handleReset() {
      this.searchForm = {
        keyword: "",
        status: ""
      }
      this.pagination.currentPage = 1
      this.loadSchoolList()
    },

    handleAdd() {
      console.log("添加学校")
      this.isEditing = false
      this.currentSchool = null
      this.resetForm()
      this.editDialogVisible = true
    },

    handleEdit(school) {
      console.log("编辑学校:", school)
      this.isEditing = true
      this.currentSchool = school
      // 复制数据到表单
      this.schoolForm = {
        id: school.id,
        name: school.name,
        address: school.address || '',
        contactPerson: school.contactPerson || '',
        contactPhone: school.contactPhone || '',
        studentCount: school.studentCount || 0,
        status: school.status || 'active'
      }
      this.editDialogVisible = true
    },

    handleView(school) {
      console.log("查看学校详情:", school)
      this.currentSchool = school
      this.viewDialogVisible = true
    },

    async handleToggleStatus(school) {
      const newStatus = school.status === 'active' ? 'disabled' : 'active'
      const action = newStatus === 'active' ? '启用' : '禁用'
      
      try {
        await this.$confirm(`确定要${action}学校「${school.name}」吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })

        this.loading = true
        try {
          // 尝试多种可能的API端点
          let response
          try {
            // 方案1: 专用的状态更新端点
            response = await this.$http.put(`/admin/schools/${school.id}/status`, {
              status: newStatus
            })
          } catch (statusError) {
            if (statusError.response && statusError.response.status === 404) {
              console.log('状态端点不存在，尝试使用通用更新端点')
              try {
                // 方案2: 使用通用的更新端点
                response = await this.$http.put(`/admin/schools/${school.id}`, {
                  ...school,
                  status: newStatus
                })
              } catch (updateError) {
                if (updateError.response && updateError.response.status === 404) {
                  console.log('通用更新端点也不存在，直接使用本地模拟')
                  throw updateError // 让外层catch处理
                } else {
                  throw updateError
                }
              }
            } else {
              throw statusError
            }
          }
          
          if (response.data.code === 200) {
            // 更新本地数据
            const index = this.schoolList.findIndex(item => item.id === school.id)
            if (index !== -1) {
              this.schoolList[index].status = newStatus
            }
            this.$message.success(`${action}成功`)
          } else {
            this.$message.error(response.data.message || `${action}失败`)
          }
        } catch (error) {
          console.error(`${action}学校失败:`, error)
          
          // 如果API不存在，使用模拟更新
          if (error.response && error.response.status === 404) {
            console.log('API端点不存在，使用本地模拟更新')
            this.isDemoMode = true // 启用演示模式提示
            const index = this.schoolList.findIndex(item => item.id === school.id)
            if (index !== -1) {
              this.schoolList[index].status = newStatus
            }
            this.$message({
              message: `${action}成功！当前为演示模式，数据仅在本地更新。`,
              type: 'success',
              duration: 4000
            })
          } else {
            this.$message.error(`${action}失败，请重试`)
          }
        } finally {
          this.loading = false
        }
      } catch (error) {
        // 用户取消操作
        if (error !== 'cancel') {
          console.error('操作异常:', error)
        }
      }
    },

    async handleDelete(school) {
      try {
        await this.$confirm(`确定要删除学校「${school.name}」吗？此操作不可恢复！`, '警告', {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning'
        })

        this.loading = true
        try {
          const response = await this.$http.delete(`/admin/schools/${school.id}`)
          
          if (response.data.code === 200) {
            this.$message.success('删除成功')
            // 重新加载列表
            await this.loadSchoolList()
          } else {
            this.$message.error(response.data.message || '删除失败')
          }
        } catch (error) {
          console.error('删除学校失败:', error)
          
          // 如果API不存在，使用本地模拟删除
          if (error.response && error.response.status === 404) {
            console.log('删除API端点不存在，使用本地模拟删除')
            this.isDemoMode = true // 启用演示模式提示
            // 从本地列表中移除
            const index = this.schoolList.findIndex(item => item.id === school.id)
            if (index !== -1) {
              this.schoolList.splice(index, 1)
              this.pagination.total = Math.max(0, this.pagination.total - 1)
            }
            this.$message({
              message: '删除成功！当前为演示模式，数据仅在本地删除。',
              type: 'success',
              duration: 4000
            })
          } else {
            this.$message.error('删除失败，请重试')
          }
        } finally {
          this.loading = false
        }
      } catch (error) {
        // 用户取消操作
        if (error !== 'cancel') {
          console.error('删除操作异常:', error)
        }
      }
    },

    async handleSave() {
      try {
        // 表单验证
        await this.$refs.schoolForm.validate()
        
        this.saving = true
        try {
          const apiUrl = this.isEditing 
            ? `/admin/schools/${this.schoolForm.id}` 
            : '/admin/schools'
          const method = this.isEditing ? 'put' : 'post'
          
          const response = await this.$http[method](apiUrl, this.schoolForm)
          
          if (response.data.code === 200) {
            this.$message.success(this.isEditing ? '保存成功' : '添加成功')
            this.editDialogVisible = false
            // 重新加载列表
            await this.loadSchoolList()
          } else {
            this.$message.error(response.data.message || (this.isEditing ? '保存失败' : '添加失败'))
          }
        } catch (error) {
          console.error('保存学校失败:', error)
          
          // 如果API不存在，使用本地模拟保存
          if (error.response && error.response.status === 404) {
            console.log('保存API端点不存在，使用本地模拟保存')
            this.isDemoMode = true // 启用演示模式提示
            
            if (this.isEditing) {
              // 模拟编辑：更新现有记录
              const index = this.schoolList.findIndex(item => item.id === this.schoolForm.id)
              if (index !== -1) {
                this.schoolList[index] = { 
                  ...this.schoolList[index], 
                  ...this.schoolForm,
                  updatedAt: new Date().toISOString()
                }
              }
              this.$message({
                message: '保存成功！当前为演示模式，数据仅在本地更新。',
                type: 'success',
                duration: 4000
              })
            } else {
              // 模拟添加：添加新记录
              const newSchool = {
                ...this.schoolForm,
                id: Date.now(), // 使用时间戳作为临时ID
                createdAt: new Date().toISOString(),
                updatedAt: new Date().toISOString()
              }
              this.schoolList.unshift(newSchool)
              this.pagination.total += 1
              this.$message({
                message: '添加成功！当前为演示模式，数据仅在本地保存。',
                type: 'success',
                duration: 4000
              })
            }
            
            this.editDialogVisible = false
          } else {
            this.$message.error(this.isEditing ? '保存失败，请重试' : '添加失败，请重试')
          }
        } finally {
          this.saving = false
        }
      } catch (error) {
        console.log('表单验证失败:', error)
      }
    },

    resetForm() {
      // 重置表单数据
      this.schoolForm = {
        id: null,
        name: '',
        address: '',
        contactPerson: '',
        contactPhone: '',
        studentCount: 0,
        status: 'active'
      }
      // 清除验证结果
      if (this.$refs.schoolForm) {
        this.$refs.schoolForm.resetFields()
      }
    },

    forceRefresh() {
      console.log("强制刷新学校列表")
      this.$message.info("正在刷新学校列表...")
      this.schoolList = [] // 清空现有数据
      this.pagination.currentPage = 1
      this.loadSchoolList()
    },

    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.pagination.currentPage = 1
      this.loadSchoolList()
    },

    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.loadSchoolList()
    },

    getStatusType(status) {
      const statusMap = {
        active: "success",
        disabled: "danger"
      }
      return statusMap[status] || "info"
    },

    getStatusName(status) {
      const statusMap = {
        active: "正常",
        disabled: "禁用"
      }
      return statusMap[status] || "未知"
    },

    formatDate(date) {
      if (!date) return '未知'
      return new Date(date).toLocaleString('zh-CN')
    },

    // 数据验证辅助方法
    validateSchoolData(schoolList) {
      if (!Array.isArray(schoolList)) {
        console.error("学校数据不是数组:", schoolList)
        return false
      }
      
      // 检查数组中的每个学校对象
      for (let i = 0; i < schoolList.length; i++) {
        const school = schoolList[i]
        if (!school || typeof school !== 'object') {
          console.error(`学校数据[${i}]不是对象:`, school)
          continue
        }
        
        // 检查必要字段
        const requiredFields = ['id', 'name']
        for (const field of requiredFields) {
          if (!Object.prototype.hasOwnProperty.call(school, field)) {
            console.warn(`学校数据[${i}]缺少字段 ${field}:`, school)
          }
        }
      }
      
      return true
    }
  }
}
</script>

<style scoped>
.school-management {
  padding: 0;
}

.search-area {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
}

.pagination-area {
  margin-top: 20px;
  text-align: right;
}

/* 对话框样式 */
.school-detail {
  padding: 10px 0;
}

.dialog-footer {
  text-align: right;
}

.dialog-footer .el-button {
  margin-left: 10px;
}

/* 表单样式优化 */
.el-form-item {
  margin-bottom: 22px;
}

.el-form-item__label {
  font-weight: 500;
  color: #606266;
}

/* 描述列表样式 */
.el-descriptions {
  margin-top: 20px;
}

.el-descriptions__label {
  font-weight: 500;
}

/* 响应式优化 */
@media (max-width: 768px) {
  .el-dialog {
    width: 95% !important;
    margin: 0 auto;
  }
  
  .el-descriptions {
    font-size: 14px;
  }
}
</style>
